using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Entities;
using Sustainalytics.Synchronization.Validation.Entities.CorporateGovernance;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.ValidationRules.CorporateGovernance
{
    public class GovernanceMissingCommentsForIndicatorsRule : Rule<GovernanceValidationProfile>
    {
        private readonly HashSet<string> indicatorsHashSet = new IndicatorsHashSet
                                                                 {
                                                                     "CG.1.1",
                                                                     "CG.2.8",
                                                                     "CG.4.5",
                                                                     "CG.4.6",
                                                                     "CG.5.3"
                                                                 };

        public override Severity Severity => Severity.Yellow;
        public override BusinessResearchProduct BusinessResearchProduct => BusinessResearchProduct.CorporateGovernance;
        public override string Code => "YR121";
        public override string InformationalMessage => "No comments for individual indicators (G.1.1, G.2.8, G.4.5, G.4.6, G.5.3)  Full Profile";

        public GovernanceMissingCommentsForIndicatorsRule()
        {
            For(x => x.GovernanceIndicators).When(Validator).WithKey(x => x.CompanyId)
                .WithMessage("The company {0} #{1}# does not have comments for indicators G.1.1, G.2.8, G.4.5, G.4.6, G.5.3  Full Profile");
        }

        private bool Validator(GovernanceValidationProfile validatedEntity, GovernanceValidationProfile referenceEntity)
        {
            //This rule will be applied only for companies with full profile
            if (!validatedEntity.FullProfile)
                return true;

            var indicators = (List<GovernanceIndicator>)GetValue(validatedEntity);

            if (indicators == null)
            {
                return false;
            }

            var triggerIndicators = indicators.Where(i => indicatorsHashSet.Contains(i.Number, StringComparer.CurrentCultureIgnoreCase)
                    && string.IsNullOrWhiteSpace(i.Comment))
                    .Select(x => x.Number);

            if (!triggerIndicators.Any())
                return true;

            SetTriggersMessages(triggerIndicators);

            return false;            
        }
    }
}